<template>
	<view class="email-verify-container">
		<!-- 自定义导航栏 -->
		<ob-navbar 
			title="邮箱验证"
			:show-back="true"
			background-color="rgba(255, 255, 255, 0.95)"
			title-color="#333333"
			:border="true"
			:prevent-default-back="true"
			@left-click="handleBackToRegister"
		/>
		
		
		<!-- 主要内容区域 -->
		<view class="content-wrapper">
			<!-- 头部说明 -->
			<view class="header-section">
				<view class="email-icon">
					<text class="icon">📮</text>
				</view>
				<text class="main-title">验证您的邮箱</text>
				<text class="desc-text">我们已向 <text class="email-highlight">{{ maskedEmail }}</text> 发送了验证码</text>
				<text class="sub-desc">请输入6位验证码完成邮箱验证</text>
			</view>
			
			<!-- 验证码输入区域 -->
			<view class="verification-section">
				<view class="code-input-container" @click="focusInput(currentInputIndex)">
					<view 
						v-for="(digit, index) in codeDigits" 
						:key="index"
						class="code-input-item"
						:class="{ 
							'code-input-active': currentInputIndex === index,
							'code-input-filled': digit !== '',
							'code-input-error': hasError 
						}"
						@click="focusInput(index)"
					>
						<text class="code-digit">{{ digit }}</text>
					</view>
				</view>
				
				<!-- 隐藏的输入框 -->
				<input 
					ref="hiddenInput"
					class="hidden-input"
					type="tel"
					inputmode="numeric"
					tabindex="0"
					autofocus
					:focus="isFocused"
					v-model="verificationCode"
					maxlength="6"
					@input="handleCodeInput"
					@focus="handleFocus"
					@blur="handleBlur"
				/>
				
				<text v-if="hasError" class="error-message">{{ errorMessage }}</text>
			</view>
			
			<!-- 重新发送区域 -->
			<view class="resend-section">
				<text class="resend-desc">没有收到验证码？</text>
				<button 
					class="resend-btn"
					:class="{ 'btn-disabled': countdown > 0 || isLoading }"
					:disabled="countdown > 0 || isLoading"
					@click="resendCode"
				>
					<text class="resend-text">
						{{ countdown > 0 ? `${countdown}秒后重发` : '重新发送' }}
					</text>
				</button>
			</view>
			
			<!-- 操作按钮 -->
			<view class="action-section">
				<button 
					class="verify-btn"
					:class="{ 'btn-disabled': !canVerify }"
					:disabled="!canVerify"
					@click="verifyCode"
				>
					<text class="btn-text">{{ isLoading ? '验证中...' : '验证并继续' }}</text>
				</button>
				
				<button class="change-email-btn" @click="changeEmail">
					<text class="change-email-text">使用其他邮箱</text>
				</button>
			</view>
			
			<!-- 提示信息 -->
			<view class="tips-section">
				<view class="tips-card">
					<text class="tips-title">💡 温馨提示</text>
					<text class="tips-content">
						• 验证码有效期为10分钟\n
						• 请检查垃圾邮件箱\n
						• 确保邮箱地址正确\n
						• 如仍未收到，请联系客服
					</text>
				</view>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="验证中..." />
	</view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import authApi from '../../api/auth.js'

// 响应式数据
const verificationCode = ref('')
const codeDigits = ref(['', '', '', '', '', ''])
const currentInputIndex = ref(0)
const hasError = ref(false)
const errorMessage = ref('')
const isLoading = ref(false)
const countdown = ref(60)
const email = ref('')
let countdownTimer = null
const hiddenInput = ref(null)
const isFocused = ref(false)

// 计算属性
const maskedEmail = computed(() => {
	if (!email.value) return ''
	const [localPart, domain] = email.value.split('@')
	if (localPart.length <= 3) {
		return `${localPart[0]}***@${domain}`
	}
	return `${localPart.substring(0, 2)}***${localPart.substring(localPart.length - 1)}@${domain}`
})

const canVerify = computed(() => {
	return verificationCode.value.length === 6 && !isLoading.value && !hasError.value
})

// 页面加载时初始化
onMounted(() => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const options = currentPage.options
	
	if (options.email) {
		email.value = decodeURIComponent(options.email)
	}
	
	// 启动倒计时
	startCountdown()
	
	// 自动聚焦到第一个输入框
	nextTick(() => {
		focusInput(0)
	})
})

// 页面卸载时清除定时器
onUnmounted(() => {
	if (countdownTimer) {
		clearInterval(countdownTimer)
	}
})


// 倒计时功能
const startCountdown = (seconds = 60) => {
	countdown.value = seconds
	countdownTimer = setInterval(() => {
		countdown.value--
		if (countdown.value <= 0) {
			clearInterval(countdownTimer)
			countdownTimer = null
		}
	}, 1000)
}

// 输入框操作
const focusInput = (index) => {
	currentInputIndex.value = index
	isFocused.value = true
}

const handleCodeInput = () => {
	// 清除错误状态
	hasError.value = false
	errorMessage.value = ''
	
	// 更新数字显示
	const code = verificationCode.value.toString()
	for (let i = 0; i < 6; i++) {
		codeDigits.value[i] = code[i] || ''
	}
	
	// 更新当前输入位置
	currentInputIndex.value = Math.min(code.length, 5)
	
	// 如果输入完6位数字，自动验证
	if (code.length === 6) {
		nextTick(() => {
			verifyCode()
		})
	}
}

const handleFocus = () => {
	// 输入框获得焦点时的处理
}

const handleBlur = () => {
	// 输入框失去焦点时的处理
}

// 验证码验证
const verifyCode = async () => {
	if (verificationCode.value.length !== 6) {
		hasError.value = true
		errorMessage.value = '请输入6位验证码'
		return
	}
	try {
		isLoading.value = true
		await authApi.verifyEmail({
			email: email.value,
			code: verificationCode.value
		})
		// 记录邮箱以便登录页自动填充
		uni.setStorageSync('rememberedAccount', email.value)
		uni.showToast({
			title: '验证成功，请登录',
			icon: 'success',
			duration: 1200
		})
		setTimeout(() => {
			uni.reLaunch({ url: `/pages/auth/login?email=${encodeURIComponent(email.value)}` })
		}, 800)
	} catch (error) {
		console.error('邮箱验证失败:', error)
		hasError.value = true
		errorMessage.value = error.message || '验证码错误，请重试'
		verificationCode.value = ''
		for (let i = 0; i < 6; i++) {
			codeDigits.value[i] = ''
		}
		currentInputIndex.value = 0
	} finally {
		isLoading.value = false
	}
}

// 重新发送验证码
const resendCode = async () => {
	try {
		// 重新发送验证码，这里需要调用注册接口重新发送
		await authApi.register({
			email: email.value,
			password: 'temp_password', // 临时密码，实际不会被使用
			username: email.value.split('@')[0]
		})
		
		uni.showToast({
			title: '验证码已重新发送',
			icon: 'success',
			duration: 2000
		})
		
		// 重新启动倒计时
		startCountdown(60)
		
	} catch (error) {
		console.error('重新发送验证码失败:', error)
		
		// 处理特定的错误情况
		let errorMessage = '发送失败，请重试'
		if (error.message) {
			if (error.message.includes('邮箱已存在') || error.message.includes('already exists')) {
				errorMessage = '该邮箱已注册，请直接登录'
			} else {
				errorMessage = error.message
			}
		}
		
		uni.showToast({
			title: errorMessage,
			icon: 'none',
			duration: 2000
		})
	}
}

// 返回注册页面
const handleBackToRegister = () => {
	uni.redirectTo({
		url: '/pages/auth/register'
	})
}

// 更换邮箱
const changeEmail = () => {
	uni.showModal({
		title: '更换邮箱',
		content: '确定要更换邮箱地址吗？这将返回到注册页面。',
		confirmText: '确定',
		cancelText: '取消',
		success: (res) => {
			if (res.confirm) {
				uni.navigateBack({
					fail: () => {
						uni.reLaunch({
							url: '/pages/auth/register'
						})
					}
				})
			}
		}
	})
}
</script>

<style lang="scss" scoped>
.email-verify-container {
	min-height: 100vh;
	background: #ffffff;
	position: relative;
	overflow: hidden;
}


.content-wrapper {
	position: relative;
	z-index: 1;
	padding: 100px 30px 40px;
}

.header-section {
	text-align: center;
	margin-bottom: 40px;
	padding: 25px 20px;
	background: rgba(0, 0, 0, 0.03);
	backdrop-filter: blur(15px);
	border-radius: 20px;
	border: 2px solid rgba(0, 0, 0, 0.15);
	box-shadow: 
		0 6px 24px rgba(0, 0, 0, 0.05),
		inset 0 1px 0 rgba(255, 255, 255, 0.8);
	
	.email-icon {
		width: 80px;
		height: 80px;
		background: rgba(0, 122, 255, 0.1);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 20px;
		border: 2px solid rgba(0, 122, 255, 0.2);
		
		.icon {
			font-size: 36px;
		}
	}
	
	.main-title {
		display: block;
		font-size: 28px;
		font-weight: bold;
		color: var(--text-color);
		margin-bottom: 12px;
	}
	
	.desc-text {
		display: block;
		font-size: 16px;
		color: var(--text-secondary);
		margin-bottom: 8px;
		line-height: 1.5;
		
		.email-highlight {
			font-weight: 600;
			color: var(--primary-color);
		}
	}
	
	.sub-desc {
		display: block;
		font-size: 14px;
		color: var(--text-secondary);
	}
}

.verification-section {
	margin-bottom: 30px;
	position: relative;
}

.code-input-container {
	display: flex;
	justify-content: center;
	gap: 12px;
	margin-bottom: 15px;
}

.code-input-item {
	width: 45px;
	height: 55px;
	background: #f8f9fa;
	border: 2px solid #e9ecef;
	border-radius: 12px;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;
	cursor: pointer;
	
	&.code-input-active {
		border-color: var(--primary-color);
		background: #ffffff;
		transform: scale(1.05);
		box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
	}
	
	&.code-input-filled {
		background: #ffffff;
		border-color: var(--primary-color);
		box-shadow: 0 2px 8px rgba(0, 122, 255, 0.15);
	}
	
	&.code-input-error {
		border-color: #ff4757;
		background: #fff5f5;
		animation: shake 0.5s ease-in-out;
	}
	
	.code-digit {
		font-size: 24px;
		font-weight: 600;
		color: #333333;
	}
}

.hidden-input {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 55px;
	opacity: 0;
	pointer-events: auto;
}

.error-message {
	display: block;
	text-align: center;
	font-size: 14px;
	color: #ff4757;
	background: rgba(255, 71, 87, 0.1);
	padding: 8px 12px;
	border-radius: 8px;
}

.resend-section {
	text-align: center;
	margin-bottom: 30px;
	
	.resend-desc {
		display: block;
		font-size: 14px;
		color: var(--text-secondary);
		margin-bottom: 10px;
	}
}

.resend-btn {
	background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
	border: none;
	border-radius: 20px;
	padding: 8px 20px;
	transition: all 0.3s ease;
	box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
	
	&.btn-disabled {
		background: #ddd;
		opacity: 0.5;
		cursor: not-allowed;
		box-shadow: none;
	}
	
	&:not(.btn-disabled):active {
		background: linear-gradient(135deg, #0051D5 0%, #003A9B 100%);
		transform: translateY(1px);
	}
	
	.resend-text {
		font-size: 14px;
		color: #FFFFFF;
	}
}

.action-section {
	margin-bottom: 30px;
}

.verify-btn {
	width: 100%;
	height: 50px;
	background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
	border: none;
	border-radius: 25px;
	margin-bottom: 15px;
	transition: all 0.3s ease;
	box-shadow: 0 6px 20px rgba(0, 122, 255, 0.3);
	
	&.btn-disabled {
		background: #ddd;
		cursor: not-allowed;
		box-shadow: none;
	}
	
	&:not(.btn-disabled):active {
		transform: scale(0.98);
		background: linear-gradient(135deg, #0051D5 0%, #003A9B 100%);
	}
	
	.btn-text {
		font-size: 18px;
		font-weight: 600;
		color: #FFFFFF;
	}
}

.change-email-btn {
	width: 100%;
	height: 45px;
	background: transparent;
	border: 1px solid var(--primary-color);
	border-radius: 22px;
	transition: all 0.3s ease;
	
	&:active {
		background: rgba(0, 122, 255, 0.1);
	}
	
	.change-email-text {
		font-size: 16px;
		color: var(--primary-color);
	}
}

.tips-section {
	margin-bottom: 20px;
}

.tips-card {
	background: rgba(0, 0, 0, 0.03);
	border-radius: 16px;
	padding: 20px;
	border: 1px solid rgba(0, 0, 0, 0.1);
	backdrop-filter: blur(10px);
	
	.tips-title {
		display: block;
		font-size: 16px;
		font-weight: 600;
		color: var(--text-color);
		margin-bottom: 12px;
	}
	
	.tips-content {
		font-size: 14px;
		color: var(--text-secondary);
		line-height: 1.6;
		white-space: pre-line;
	}
}


@keyframes shake {
	0%, 100% {
		transform: translateX(0);
	}
	25% {
		transform: translateX(-5px);
	}
	75% {
		transform: translateX(5px);
	}
}
</style>